#include <49func.h>
int main(int argc, char *argv[])
{
    // ./6_server_epoll_ET 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;//服务端地址
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int reuse = 1; // SO_REUSEADDR属性的参数
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(int));
    ERROR_CHECK(ret,-1,"setsockopt"); 
    ret = bind(sockfd, (struct sockaddr *)&addr,sizeof(addr));
    ERROR_CHECK(ret,-1,"bind");
    listen(sockfd,10);
    struct sockaddr_in clientAddr;
    socklen_t clientAddrSize = sizeof(clientAddr);//该变量必须初始化
    //socklen_t clientAddrSize = 0;
    int netfd = accept(sockfd,(struct sockaddr *)&clientAddr,&clientAddrSize);
    printf("netfd = %d\n",netfd);
    printf("client ip = %s, port = %d\n", 
           inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
    int epfd = epoll_create(1); //epoll_create 取代定义fd_set
    struct epoll_event event;
    event.data.fd = STDIN_FILENO;
    event.events = EPOLLIN;
    epoll_ctl(epfd,EPOLL_CTL_ADD,STDIN_FILENO,&event); // FD_SET
    event.data.fd = netfd;
    event.events = EPOLLIN|EPOLLET;//给socket增加边缘触发属性
    epoll_ctl(epfd,EPOLL_CTL_ADD,netfd,&event);
    //  char buf[4096];
    char buf[3];
    while(1){
        struct epoll_event readySet[2];
        int readyNum = epoll_wait(epfd,readySet,2,-1);
        printf("epoll_wait ready!\n");
        for(int i = 0; i < readyNum; ++i){
            if(readySet[i].data.fd == STDIN_FILENO){
                bzero(buf,sizeof(buf));
                ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
                if(sret == 0){
                    send(netfd,"nishigehaoren",13,0);
                    goto end;
                }
                send(netfd,buf,sret,0);
            }
            else if(readySet[i].data.fd == netfd){
                bzero(buf,sizeof(buf));
                ssize_t sret;
                while(1){
                    bzero(buf,sizeof(buf));
                    sret = recv(netfd,buf,sizeof(buf)-1,MSG_DONTWAIT);
                    printf("sret = %ld, buf = %s\n", sret, buf);
                    if(sret == -1){
                        break;
                    }
                    else if(sret == 0){
                        printf("hehe\n");
                        goto end;
                    }
                }
            }
        }
    }
end:
    close(netfd);
    close(sockfd);
    return 0;

}

